package com.yutel.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class ValidateImageCode {
	private final static char[] Tables = "0123456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz".toCharArray();
	private final static Color[] color = new Color[] { Color.BLACK, Color.BLUE,Color.RED };
	private final static Random random = new Random();

	/**
	 * 产生随机颜色
	 * 
	 * @param fc
	 * @param bc
	 * @return
	 */
	public static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * 产生验证码
	 */
	public void image(OutputStream os) throws IOException {
		// 在内存中创建图象
		int width = 50, height = 20;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) bi.getGraphics();
		// 干扰线
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		for (int i = 0; i < 85; i++) {
			g.setColor(getRandColor(150, 250));
			g.drawLine(0, random.nextInt(height), width, random.nextInt(height));
		}
		// 验证码
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			int index = random.nextInt(Tables.length);
			g.setColor(color[random.nextInt(color.length)]);
			g.setFont(new Font("Fixedsys", Font.BOLD, 16 + random.nextInt(2)));// 输出的字体和大小
			g.drawString("" + Tables[index], (i * 11) + 5, 16);// 写什么数字，在图片的什么位置画
			result.append(Tables[index]);
		}
		// 图象生效
		g.dispose();
		// 输出图象到页面
		ImageIO.write(bi, "JPEG", os);
	}

	public static void main(String[] args) {
		try {
			ValidateImageCode vic = new ValidateImageCode();
			FileOutputStream ops = new FileOutputStream("d:\\d.jpg");
			vic.image(ops);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}